package com.waidi.clothespad.fragment;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DownloadManager;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ScaleXSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.waidi.clothespad.R;
import com.waidi.clothespad.adapter.BaseInfoAdapter;
import com.waidi.clothespad.adapter.DuoXuanAdapter;
import com.waidi.clothespad.adapter.ListviewData;
import com.waidi.clothespad.adapter.MyListViewAdapter;
import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.Db;
import com.waidi.clothespad.common.FaultInfo;
import com.waidi.clothespad.common.MyToast;
import com.waidi.clothespad.common.Qccxzjlxt;
import com.waidi.clothespad.ui.EasyPickerView;
import com.waidi.clothespad.ui.WaitDialog;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/4/26.
 */

public class FragHouDaoqc extends Fragment {
    private static final String TAG = "FragHouDaoqc:";
    Unbinder unbinder;
    @BindView(R.id.fault_commit_bt)
    Button fault_bt;

    @BindView(R.id.pd_order_finished_number)
    TextView pd_order_finished_number;


    @BindView(R.id.today_finshed_num)
    TextView today_finshed_num;

    @BindView(R.id.today_bad_num)
    TextView today_bad_num;

    @BindView(R.id.today_ok_rate)
    TextView today_ok_rate;


    private View view;
    public Context context;
    private Db myDbHelper =null;
    public Gyinfo handler =null;


    PopupWindow popupWindow;
    LayoutInflater inflater;
    private List<Map<String, Object>> dataList;
    private SimpleAdapter adapter;
    private GridView gridView;
    private PullToRefreshGridView gridview = null;
    private ListView listView;
    private TextView tv;
    private Button bt;
    public BaseInfoAdapter myadapter=null;
    public DuoXuanAdapter duoxuanadapter = null;

    private MyListViewAdapter mAdapter = null;
    private List<ListviewData> mData = null;
    private WaitDialog waitDialog =null;
    private EasyPickerView epvH =null;
    private TextView tvdes =null;
    private int hour;

    private  boolean loading = false;

    private  boolean  onDetach = false;

    public  ArrayList<dpshoudaoqclxt> dpshoudaoqclxts =null;

    /**
     * 用了存放点击的gridview的item的pos和这个pos的选中状态
     */
    private Map<Integer,Boolean> gvChooseMap=new HashMap<Integer, Boolean>();


    public FragHouDaoqc()
    {
        handler = new Gyinfo();
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.frag_product_houdao_qc, container, false);
        unbinder = ButterKnife.bind(this, view);
        onDetach = false ;

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        onDetach = false ;

        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //initParam();
        //initElem();



        listView = (ListView) view.findViewById(R.id.list_process_sheet);
        gridview = (PullToRefreshGridView)view.findViewById(R.id.gridview);



        List<String> name = new ArrayList();
        name.add("101");
        duoxuanadapter = new DuoXuanAdapter(context,name);
        gridview.setAdapter(duoxuanadapter);
        duoxuanadapter.notifyDataSetChanged();

// gridview的item的点击事件  OnItemClickListener
/*        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("onItemClick", Integer.toString(position));
               //Toast.makeText(context, Integer.toString(position), Toast.LENGTH_LONG).show();
                myadapter.setSeclection(position);
                myadapter.notifyDataSetChanged();
            }
        });*/

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos,
                                    long arg3) {
                if(view.isActivated()){
                    view.setActivated(false);
                   // gvChooseMap.put(pos, false);
                }else{
                    view.setActivated(true);
                  //gvChooseMap.put(pos, true);
                }
                duoxuanadapter.notifyDataSetChanged();
            }
        });


        gridview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                // Toast.makeText(context, "Pull Down!", Toast.LENGTH_SHORT).show();
                String url = "http://" + Config.devConfig.web_addr + "/js/a/its/terminal/faultInfo?";
                sendRequestDefect(url);
                new FragHouDaoqc.GetDataTask().execute();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //  Toast.makeText(context, "Pull Up!", Toast.LENGTH_SHORT).show();
                new FragHouDaoqc.GetDataTask().execute();
            }
        });



        initData();

        fault_bt.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {

                int fault_num = duoxuanadapter.getSelectNum();
                if(fault_num<=0)
                {
                    Toast.makeText(context, "未选择返修原因！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(Config.qccxzjlxt.order_id.length()==0)
                {
                    Toast.makeText(context, "订单号为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(mAdapter.getSelection()<0)
                {
                    Toast.makeText(context, "返修工序未选择！", Toast.LENGTH_SHORT).show();
                    return;
                }
                else
                {
                    try
                    {

                  /*      // 带“是”和“否”的提示框
                        AlertDialog.Builder  dialog = new AlertDialog.Builder(context);

                        dialog.setTitle("确定提交返修工序吗？")
                                .setMessage("确定吗")
                                .setPositiveButton("是", null)
                                .setNegativeButton("否", null)
                                .show();

                        Log.i(TAG,"=========================");*/




                        int a = 0;/*ITS 返修提交*/
                        if(a==1)
                        {
                            JSONObject commit = new JSONObject();
                            commit.put("orderCode", Config.qccxzjlxt.order_id);
                            commit.put("terminalCode", Config.devConfig.devid);

                            int selection = mAdapter.getSelection();
                            if (selection < Config.qccxzjlxt.gxinfoArrayList.size())
                                commit.put("procedureCode", Config.qccxzjlxt.gxinfoArrayList.get(selection).opera_code);
                            else
                            {
                                Log.i(TAG, "selection err!");
                                return;
                            }

                            commit.put("devid", Config.devConfig.devid);
                            JSONArray faultcodearray = new JSONArray();
                            int k = 0;
                            for (int i = 0; i < duoxuanadapter.faultInfoArrayList.size(); i++) {
                                if (duoxuanadapter.faultInfoArrayList.get(i).clickedList != 0) {
                                    faultcodearray.put(k, duoxuanadapter.faultInfoArrayList.get(i).clickedList);
                                    k++;
                                }
                            }
                            commit.put("faultCodeList", faultcodearray);
                            String path = "http://" + Config.devConfig.web_addr + "/js/a/its/terminal/uploadFaultByLine?";
                            String result;
                            try {
                                result = URLEncoder.encode(commit.toString(), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                                return;
                            }
                            String url = path + "info=" + result;
                            sendRequestFaultInfo(url);
                            Log.i(TAG, url);
                        }

                        int b = 1;/*DPS产线 返修提交*/
                        if(b==1)
                        {

                            JSONObject commitdps = new JSONObject();
                            JSONArray faultcodearray = new JSONArray();
                            int k = 0;
                            for (int i = 0; i < duoxuanadapter.faultInfoArrayList.size(); i++)
                            {
                                if (duoxuanadapter.faultInfoArrayList.get(i).clickedList != 0) {
                                    faultcodearray.put(k, duoxuanadapter.faultInfoArrayList.get(i).clickedList);
                                    k++;
                                }
                            }
                            commitdps.put("faultCodeList", faultcodearray);

                            String pathdps = "http://" + Config.devConfig.web_addr + "/pis/defect/addTypeInfo?";
                            String po = "po="+Config.qccxzjlxt.order_id;
                            String type="&typeInfo="+commitdps.toString();
                            String name ="&name=";
                            String code="&code=";


                            int selection = mAdapter.getSelection();
                            if (selection < Config.qccxzjlxt.gxinfoArrayList.size())
                            {
                                name = name +Config.qccxzjlxt.gxinfoArrayList.get(selection).opera_desc;
                                code = code +Config.qccxzjlxt.gxinfoArrayList.get(selection).opera_code;
                            }
                            else
                            {
                                Log.i(TAG, "selection err!");
                                return;
                            }

                            String dpsresult="";
                            String ss = po+type+name+code;
                            try
                            {
                                dpsresult = URLEncoder.encode(ss, "utf-8");
                            }
                            catch (UnsupportedEncodingException e)
                            {
                                e.printStackTrace();
                                return;
                            }
                            String url = pathdps+dpsresult;
                            sendDpsRequestFaultInfo(url);

                        }

                        int c = 1;

                        if(c==1)
                        {






                        }


                    }catch (JSONException e)
                    {
                        Log.i(TAG,e.toString());
                        e.printStackTrace();
                    }
                }
            }

        });


    }
    private void initWaitDialog()
    {
        waitDialog = new WaitDialog(context);
        waitDialog.setText("正在提交...");
    }


    private void initHours() {
        epvH = (EasyPickerView)view.findViewById(R.id.epv_h);
        tvdes = (TextView) view.findViewById(R.id.tv);
        final ArrayList<String> hDataList = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            hDataList.add("" + i);

        epvH.setDataList(hDataList);
        epvH.setOnScrollChangedListener(new EasyPickerView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int curIndex) {
                hour = Integer.parseInt(hDataList.get(curIndex));
                tvdes.setText(hour+"件不合格");
            }

            @Override
            public void onScrollFinished(int curIndex) {
                hour = Integer.parseInt(hDataList.get(curIndex));
                tvdes.setText(hour+"件不合格");
            }
        });
    }

    void initData()
    {

        initHours();
        initWaitDialog();

        dpshoudaoqclxts = new ArrayList<dpshoudaoqclxt>();

        mData = new LinkedList<ListviewData>();
        ListviewData list0 = new ListviewData(R.mipmap.worker,"黄小华 01","挂片-01",false);
        ListviewData list1 = new ListviewData(R.mipmap.worker,"黄小华 02","两层衣片平缝后，毛缝单边坐倒，正面压一道明线",false);
        ListviewData list2 = new ListviewData(R.mipmap.worker,"黄小华 03","把包边缝面料两边折光，折烫成双层，下层略宽于上层",false);
        ListviewData list3 = new ListviewData(R.mipmap.worker,"黄小华 04","两层衣片反面相叠，平缝0.1寸缝头后把毛丝修剪整齐",false);
        ListviewData list4 = new ListviewData(R.mipmap.worker,"黄小华 05","把衣片夹在中间，沿上层边缘缉0.1cm清止口，把上、中、下三层一起缝牢",false);
        ListviewData list5 = new ListviewData(R.mipmap.worker,"黄小华 06","翻转后正面相叠合缉0.3寸，把第一道毛缝包在里面",false);

        ListviewData list6 = new ListviewData(R.mipmap.worker,"黄小华 07","007",false);
        ListviewData list7 = new ListviewData(R.mipmap.worker,"黄小华 08","008",false);
        ListviewData list8 = new ListviewData(R.mipmap.worker,"黄小华 09","009",false);
        ListviewData list9 = new ListviewData(R.mipmap.worker,"黄小华 10","010",false);

        mData.add(list0);
        mData.add(list1);
        mData.add(list2);
        mData.add(list3);
        mData.add(list4);
        mData.add(list5);
        mData.add(list6);
        mData.add(list7);

        mData.add(list8);
        mData.add(list9);


       File gylxt = new File(Config.dpsHoudaodpsProuductIndotxt);
        if(gylxt.exists()) {
            try {
                FileInputStream in = new FileInputStream(gylxt);
                int len = 0;
                byte[] buf = new byte[1024];
                String strbuf;
                String strjson = "";
                while ((len = in.read(buf)) != -1) {
                    strbuf = new String(buf, 0, len);
                    strjson = strjson + strbuf;
                }
                in.close();
                if (strjson == null)
                    return;


                JSONObject jsonObj = new JSONObject(strjson);
                if (jsonObj == null)
                    return;

                //dps 后道qc
                JSONArray j_dpsdataArray = jsonObj.getJSONArray("data");
                if (j_dpsdataArray == null) {

                } else {
                    int size = 0;
                    size = j_dpsdataArray.length();

                    for (int i = 0; i < size; i++)
                    {
                        JSONObject stationinfo = j_dpsdataArray.optJSONObject(i);
                        String station = stationinfo.optString("station");

                        Log.i(TAG, station);
                        JSONArray namelist = stationinfo.getJSONArray("nameJsonList");
                        dpshoudaoqclxt tmp = new dpshoudaoqclxt(station);

                        for (int k = 0; k < namelist.length(); k++) {
                            String des = namelist.optJSONObject(k).optString("name");
                            String descode = namelist.optJSONObject(k).optString("code");
                            dpshoudaoqclxt.namelist t = tmp.new namelist(des, descode);
                            tmp.qcnamelist.add(t);
                            Log.i(TAG, des);
                            Log.i(TAG, descode);
                        }
                        dpshoudaoqclxts.add(tmp);
                    }

                    List<ListviewData> listdata = new LinkedList<ListviewData>();
                    for(int i = 0 ;i<dpshoudaoqclxts.size();i++)
                    {
                        String name = dpshoudaoqclxts.get(i).station;

                        for(int k = 0;k<dpshoudaoqclxts.get(i).qcnamelist.size();k++)
                        {
                            String des = dpshoudaoqclxts.get(i).qcnamelist.get(k).name;
                            String code = dpshoudaoqclxts.get(i).qcnamelist.get(k).code;
                            String content0 = des + " " +"("+code+")";
                            ListviewData tmp = new ListviewData(R.mipmap.worker,content0,des,false);
                            listdata.add(tmp);
                        }
                    }
                    mAdapter = new MyListViewAdapter((LinkedList<ListviewData>) listdata,context);
                    listView.setAdapter(mAdapter);
                    Toast.makeText(context, "后道工序列表更新成功！。。", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException je) {
                je.printStackTrace();
                Toast.makeText(context, je.toString(), Toast.LENGTH_SHORT).show();


            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();

            }
        }
        else
        {
            mAdapter = new MyListViewAdapter((LinkedList<ListviewData>) mData,context);
            listView.setAdapter(mAdapter);
        }

        if(mAdapter.getCount()!=0) //default
        {
            mAdapter.setSelectPosition(0);
        }

        //给listview设置item的点击监听
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
            {
                mAdapter.setSelectPosition(position);

            }
        });

    }


    public void initParam()
    {

/*      inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.frag_product_qc, null);
        contentview.setFocusable(true);
        contentview.setFocusableInTouchMode(true);
        initContentview(contentview);




        initEditTextEvent(contentview);
        popupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00005511));
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        myDbHelper = new Db(context,"tps10.db",null,1);*/
    }

    public void initElem()
    {
/*        llShaixuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.showAtLocation(view,  Gravity.RIGHT, 0, 0);
            }
        });*/

    }
    private  Button btn_confirm;
    private  Button btn_reset;
    private String[] ptime = new String[2];
    public void initContentview(View contentview)
    {




/*      btn_confirm = (Button) contentview.findViewById(R.id.btn_confirm);
        btn_reset = (Button) contentview.findViewById(R.id.btn_reset);
        btn_confirm.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
*//*                tableview.setHeader("产生时间", "订单编号","订单款号","款式尺寸/颜色","工序代码","员工姓名");
                tableview.refreshTable();*//*
                boolean ret = queryData(myDbHelper);
                if (!ret)
                showAlertDialog("无记录",0);
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {

                ptime_s.setText("");
                ptime_s.clearFocus();
                ptime_e.setText("");
                ptime_e.clearFocus();

            }
        });*/

    }

    private void showAlertDialog(String msg, final int type) {
        AlertDialog.Builder builder= new AlertDialog.Builder(context);
        builder.setTitle("注意").setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //ok
                popupWindow.dismiss(); //隐藏

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //cancle
                popupWindow.dismiss(); //隐藏
            }

        });
        builder.show();
    }

    @Override
    public void onStart()
    {
        super.onStart();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        onDetach  =true;
    }

    //自定义handler类
    class Gyinfo extends Handler {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg) {
            Log.i("GYINFO",Integer.toString(msg.arg1));

            if(onDetach != false )
                return;

            try {


                switch (msg.arg1) {
                    case 77: //后道工艺列表更新
                        List<ListviewData> listdata = new LinkedList<ListviewData>();
                        ;
                        for (int i = 0; i < dpshoudaoqclxts.size(); i++) {
                            String name = dpshoudaoqclxts.get(i).station;

                            for (int k = 0; k < dpshoudaoqclxts.get(i).qcnamelist.size(); k++) {
                                String des = dpshoudaoqclxts.get(i).qcnamelist.get(k).name;
                                String code = dpshoudaoqclxts.get(i).qcnamelist.get(k).code;
                                String content0 = des + " " + "(" + code + ")";
                                ListviewData tmp = new ListviewData(R.mipmap.worker, content0, des,false);
                                listdata.add(tmp);
                            }
                        }
                        mAdapter = new MyListViewAdapter((LinkedList<ListviewData>) listdata, context);
                        listView.setAdapter(mAdapter);
                        Toast.makeText(context, "后道工序列表更新成功！。。", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:  //缺陷列表更新
                        duoxuanadapter.faultInfoArrayList.clear();
                        for (int i = 0; i < Config.faultInfoArrayList.size(); i++) {
                            duoxuanadapter.faultInfoArrayList.add(Config.faultInfoArrayList.get(i));
                        }
                        gridview.setAdapter(duoxuanadapter);
                        duoxuanadapter.clear();
                        duoxuanadapter.notifyDataSetChanged();

                        Toast.makeText(context, "缺陷列表更新成功！。。", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:

                        String ss = "缺陷列表更新失败: " + msg.obj.toString();
                        Toast.makeText(context, ss, Toast.LENGTH_SHORT).show();
                        break;
                    case 4:

                        String sss = "缺陷列表更新失败: 网络错误" + msg.obj.toString();
                        Toast.makeText(context, sss, Toast.LENGTH_SHORT).show();
                        break;

                    case 10:
                        break;
                    case 11:
                        Toast.makeText(context, "返修成功!", Toast.LENGTH_SHORT).show();
                        break;
                    case 12:
                        Toast.makeText(context, "返修失败!", Toast.LENGTH_SHORT).show();
                        break;
                    case 13:
                    case 14:

                        String s = "返修失败: " + msg.obj.toString();
                        Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
                        break;


                    default:
                        break;
                }
            }
            catch (Exception e)
            {
               e.printStackTrace();
                MyToast.showToast(context,e.toString());
            }
        }
    }


    private void sendRequestFaultInfo(final String url)
    {
        httpCommitFault thread = new httpCommitFault(handler,context,url);
        thread.start();
    }


    public class httpCommitFault extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;

        public httpCommitFault(Handler handlerin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run()
        {
            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(Url);
            int code = -1;
            try {
                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get call reponse code: "+Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                    try {
                        JSONObject jsonObj = new JSONObject(result);
                        if (jsonObj == null)
                            return;

                        String res = jsonObj.optString("result");
                        if(res.compareTo("true")==0)
                        {
                            Log.i(TAG,"返修成功！！");
                            msg1=handler0.obtainMessage();//每发送一次都要重新获取
                            msg1.arg1 = 11;
                            msg1.obj = code;
                            handler0.sendMessage(msg1);
                        }
                        else
                        {
                            Log.i(TAG,"返修失败！");
                            msg1=handler0.obtainMessage();//每发送一次都要重新获取
                            msg1.arg1 = 12;
                            msg1.obj = code;
                            handler0.sendMessage(msg1);
                        }
                    }
                    catch (JSONException e)
                    {

                        e.printStackTrace();
                    }
                }
                else
                {
                    msg1=handler0.obtainMessage();//每发送一次都要重新获取
                    msg1.arg1 = 13;
                    msg1.obj = code;
                    handler0.sendMessage(msg1);
                }
            }catch (Exception e)
            {
                msg1=handler0.obtainMessage();//每发送一次都要重新获取
                msg1.arg1 = 14;
                msg1.obj = code;
                handler0.sendMessage(msg1);
                Log.e(TAG, "HTTP request err......");
                e.printStackTrace();
                return;
            }
        }

    }


    private void sendDpsRequestFaultInfo(final String url)
    {
        httpDpsCommitFault thread = new httpDpsCommitFault(handler,context,url);
        waitDialog.show();//loading......
        thread.start();
    }


    public class httpDpsCommitFault extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;

        public httpDpsCommitFault(Handler handlerin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run()
        {
            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();
            httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,4000);//连接时间
            httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
            HttpGet httpGet = new HttpGet(Url);
            int code = -1;
            try {
                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                waitDialog.dismiss();

                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get call reponse code: "+Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                    try {

                        JSONObject jsonObj = new JSONObject(result);
                        if (jsonObj == null)
                            return;
                        JSONObject error =  jsonObj.optJSONObject("error");
                        if(error!=null)
                        {
                            Log.i(TAG,"返修错误！！");
                            String message = error.optString("message");
                            String s = "返修错误："+message;
                            Looper.prepare();
                            Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
                            Looper.loop();

                        }
                        else
                        {
                            JSONObject data =  jsonObj.optJSONObject("data");
                            Log.i(TAG,"返修成功！！");
                            if(data!=null)
                            {
                                String s = "返修成功";
/*                                JSONObject todaytotal = data.optJSONObject("total");
                                JSONObject todaydefect = data.optJSONObject("defect");
                                JSONObject orderfinshed = data.optJSONObject("orderRegular");
                                JSONObject todayrate =data.optJSONObject("rate");*/

                                String todaytotalvalue=data.optString("total");
                                String todaydefectvalue=data.optString("defect");
                                String orderfinshedvalue=data.optString("orderRegular");
                                String todayratevalue=data.optString("rate");
/*                                if(todaytotal!=null)
                                {
                                    todaytotalvalue = todaytotal.toString();
                                }

                                if(todaydefect!=null)
                                {
                                    todaydefectvalue = todaydefect.toString();
                                }
                                if(orderfinshed!=null)
                                {
                                    orderfinshedvalue = orderfinshed.toString();
                                }
                                if(todayrate!=null)
                                {
                                    todayratevalue = todayrate.toString();
                                }*/

                              /*  刷新界面*/

                                File dpsProuductIndotxt = new File(Config.dpsProuductIndotxt);
                                OutputStream os = new FileOutputStream(dpsProuductIndotxt);
                                byte b[] = jsonObj.toString().getBytes("UTF-8");
                                os.write(b);
                                os.close();

                                Looper.prepare();
                                pd_order_finished_number.setText(todaytotalvalue);
                                today_finshed_num.setText(orderfinshedvalue);
                                today_bad_num.setText(todaydefectvalue);
                                today_ok_rate.setText(todayratevalue);
                                Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        }
                    }
                    catch (JSONException e)
                    {

                        e.printStackTrace();
                        Looper.prepare();
                        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }
                else
                {
/*                    msg1=handler0.obtainMessage();//每发送一次都要重新获取
                    msg1.arg1 = 13;
                    msg1.obj = code;
                    handler0.sendMessage(msg1);*/

                    Looper.prepare();

                    Toast.makeText(context, "服务端返回："+Integer.toString(code), Toast.LENGTH_SHORT).show();
                    Looper.loop();

                }
            }catch (Exception e)
            {
      /*          msg1=handler0.obtainMessage();//每发送一次都要重新获取
                msg1.arg1 = 14;
                msg1.obj = code;
                handler0.sendMessage(msg1);*/
                Log.e(TAG, "HTTP request err......");

                Looper.prepare();
                waitDialog.dismiss();
                Toast.makeText(context, "网络错误："+e.toString(), Toast.LENGTH_LONG).show();
                Looper.loop();

                e.printStackTrace();
                return;
            }


        }

    }




    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(800);
            } catch (InterruptedException e)
            {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
/*            mListItems.addFirst("Added after refresh...");
            mListItems.addAll(Arrays.asList(result));*/

/*            String url = "http://" + Config.devConfig.web_addr + "/js/a/its/terminal/faultInfo?";
            sendRequestDefect(url);*/



           // duoxuanadapter.faultInfoArrayList.clear();
           // gridview.setAdapter(duoxuanadapter);
           // duoxuanadapter.notifyDataSetChanged();


            gridview.onRefreshComplete();
            super.onPostExecute(result);
        }
    }

    public void sendRequestDefect(String url)
    {
        httpgetdefect thread = new httpgetdefect(handler,context,url);
        thread.start();
    }

    public class httpgetdefect extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;

        public httpgetdefect(Handler handlerin, Context contextin, String url)
        {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run()
        {
            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();

            httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000);//连接时间
            httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间


            HttpGet httpGet = new HttpGet(Url);
            int code = -1;
            try {
                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get call reponse code: "+Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                    try {
                        JSONObject jsonObj = new JSONObject(result);
                        if (jsonObj == null)
                            return;

                        String res = jsonObj.optString("result");
                        if(res.compareTo("true")==0)
                        {
                            Log.i(TAG,"获取缺陷成功！");
                            JSONArray qcArray = jsonObj.getJSONArray("data");
                            if(qcArray==null)
                                return;
                            if(qcArray.length()!=0)
                                Config.faultInfoArrayList.clear();
                            for (int i=0;i<qcArray.length();i++)
                            {
                                JSONObject s= (JSONObject)qcArray.get(i);
                                FaultInfo tmp = new FaultInfo();
                                tmp.fault_name =s.optString("fault_name");
                                tmp.fault_code = s.optString("fault_code");
                                tmp.clickedList = 0;
                                Config.faultInfoArrayList.add(tmp);
                            }
                            File gylxt = new File(Config.faultinfotxt);
                            OutputStream os = new FileOutputStream(gylxt);
                            byte b[] = jsonObj.toString().getBytes("UTF-8");
                            os.write(b);
                            os.close();
                            msg1=handler0.obtainMessage();//每发送一次都要重新获取
                            msg1.arg1 = 2;
                            msg1.obj = code;
                            handler0.sendMessage(msg1);

                        }
                        else
                        {
                            Log.i(TAG,"获取缺陷失败0！");
                            String ss = jsonObj.optString("message");

                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                        Looper.prepare();
                        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }
                else
                {
                    Log.i(TAG,"获取缺陷失败1！");
                    Looper.prepare();
                    Toast.makeText(context, "获取缺陷失败,服务端返回："+Integer.toString(code), Toast.LENGTH_SHORT).show();
                    Looper.loop();


                }

            }catch (Exception e)
            {
                e.printStackTrace();
                Looper.prepare();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;
            }
        }
    }

    public void httpquestFaultInfo()
    {
        String result = "";
        HttpClient httpCient = new DefaultHttpClient();
        String url = "http://" + Config.devConfig.web_addr + "/js/a/its/terminal/faultInfo?";
        HttpGet httpGet = new HttpGet(url);
        int code = -1;
        try {
            Log.i(TAG, url);
            HttpResponse response = httpCient.execute(httpGet);
            code = response.getStatusLine().getStatusCode();
            Log.i(TAG, "get call reponse code: "+Integer.toString(code));
            if (response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, HTTP.UTF_8);
                Log.i(TAG, result);
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj == null)
                        return;
                    String res = jsonObj.optString("result");
                    if(res.compareTo("true")==0)
                    {
                        Log.i(TAG,"获取缺陷成功！");
                        JSONArray qcArray = jsonObj.getJSONArray("data");
                        if(qcArray==null)
                            return;
                        if(qcArray.length()!=0)
                            Config.faultInfoArrayList.clear();
                        for (int i=0;i<qcArray.length();i++)
                        {
                            JSONObject s= (JSONObject)qcArray.get(i);
                            FaultInfo tmp = new FaultInfo();
                            tmp.fault_name =s.optString("fault_name");
                            tmp.fault_code = s.optString("fault_code");
                            tmp.clickedList = 0;
                            Config.faultInfoArrayList.add(tmp);
                        }
                        File gylxt = new File(Config.faultinfotxt);
                        OutputStream os = new FileOutputStream(gylxt);
                        byte b[] = jsonObj.toString().getBytes("UTF-8");
                        os.write(b);
                        os.close();

                        duoxuanadapter.faultInfoArrayList.clear();
                        for(int i=0;i<Config.faultInfoArrayList.size();i++)
                        {
                            duoxuanadapter.faultInfoArrayList.add(Config.faultInfoArrayList.get(i));
                        }
                        gridview.setAdapter(duoxuanadapter);
                        duoxuanadapter.clear();
                        duoxuanadapter.notifyDataSetChanged();
                        Toast.makeText(context, "获取缺陷信息成功!", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        String errmessage = jsonObj.optString("message");
                        Log.i(TAG,errmessage);
                        Toast.makeText(context, errmessage, Toast.LENGTH_SHORT).show();
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                String err = "获取缺陷错误:"+Integer.toString(code);
                Log.i(TAG,err);
                Toast.makeText(context, err, Toast.LENGTH_SHORT).show();
            }

        }catch (Exception e)
        {
            Log.e(TAG, "HTTP request err......");
            e.printStackTrace();
            return;
        }
    }

    public void dpsgetProcedureInfo(String orderid,String styleid,String num,String line)
    {
        if(loading == true)
        {
            Log.i(TAG,"当前有刷卡请求正在进行。。。");
            return;
        }


        TextView tv_id = (TextView)view.findViewById(R.id.pd_order_id);
        tv_id.setText(orderid);

        TextView tv_style = (TextView)view.findViewById(R.id.pd_style_id);
        tv_style.setText(styleid);

        TextView tv_order_num = (TextView)view.findViewById(R.id.pd_order_number);
        tv_order_num.setText(num);

        TextView tv_line_num = (TextView)view.findViewById(R.id.pd_line);
        tv_line_num.setText(line);



        String path ="http://" + Config.devConfig.web_addr+"/pis/inspectTotal/routeInfo?";
        String url=path+"po="+orderid +"&lineNum="+line;
        httploadProcedureInfo thread = new  httploadProcedureInfo(handler,context,url);

        waitDialog.show();//loading......
        thread.start();
    }

    public class httploadProcedureInfo extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;



        public httploadProcedureInfo(Handler handlerin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run() {

            Message msg1;
            String result = "";
            String imageUrl = "";
            HttpClient httpCient = new DefaultHttpClient();
            httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000);//连接时间
            httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间


            HttpGet httpGet = new HttpGet(Url);
            int code = -1;
            try {
                Log.i(TAG, Url);
                loading = true;
                HttpResponse response = httpCient.execute(httpGet);
                loading = false;
                waitDialog.dismiss();



                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get orderinfo reponse code: "+Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                }
                else
                {
                    Looper.prepare();
                    String s = "请求返回:"+Integer.toString(code);
                    Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
                    Looper.loop();
                    return;
                }
            }
            catch (Exception e)
            {
                Log.e(TAG, "HTTP request err......");
                e.printStackTrace();
                waitDialog.dismiss();
                loading = false;


                Looper.prepare();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                Looper.loop();


                return;
            }
            try
            {
                JSONObject jsonObj = new JSONObject(result);
                if (jsonObj == null)
                    return;
                else
                {
                    //dps 后道qc
                    JSONArray j_dpsdataArray = jsonObj.getJSONArray("data");
                    if(j_dpsdataArray==null)
                    {
                        JSONObject error = jsonObj.optJSONObject("error");
                        if(error!=null)
                        {
                            String message = error.optString("message");
                            Looper.prepare();
                            Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                            Looper.loop();
                            // tip
                        }
                    }
                    else
                    {
                        int size = 0;
                        size = j_dpsdataArray.length();

                        for(int i = 0 ;i<size ;i++)
                        {
                            JSONObject stationinfo = j_dpsdataArray.optJSONObject(i);
                            String station = stationinfo.optString("station");

                            Log.i(TAG,station);

                            JSONArray namelist = stationinfo.getJSONArray("nameJsonList");

                            dpshoudaoqclxt tmp = new dpshoudaoqclxt(station);

                            for(int k=0;k<namelist.length();k++)
                            {
                                String des = namelist.optJSONObject(k).optString("name");
                                String descode = namelist.optJSONObject(k).optString("code");
                                dpshoudaoqclxt.namelist t= tmp.new namelist(des,descode);
                                tmp.qcnamelist.add(t);

                                Log.i(TAG,des);
                                Log.i(TAG,descode);

                            }
                            dpshoudaoqclxts.add(tmp);
                        }




                        msg1=handler0.obtainMessage();//每发送一次都要重新获取
                        msg1.arg1 = 77;
                        handler0.sendMessage(msg1);


                        File dpshoudaoProuductIndotxt = new File(Config.dpsHoudaodpsProuductIndotxt);
                        OutputStream os = new FileOutputStream(dpshoudaoProuductIndotxt);
                        byte b[] = jsonObj.toString().getBytes("UTF-8");
                        os.write(b);
                        os.close();

                    }
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                Looper.prepare();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;
            }
            catch (Exception e)
            {

                e.printStackTrace();
                Looper.prepare();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                Looper.loop();
                return;

            }


        }

    }



    public class dpshoudaoqclxt
    {
        String station;
        public  ArrayList<namelist> qcnamelist = null;

        public dpshoudaoqclxt(String _station)
        {
            station  =_station ;
            qcnamelist = new ArrayList<namelist>();
        };

        public class namelist
        {
            String name;
            String code;
            public  namelist (String _name,String _code)
            {
                name = _name;
                code = _code;
            }
        }
    }











}
